//初始化表格
var footer;
var initGrid = function(){
	$('#enterprise').dataTable({
		"bProcessing" : true, //DataTables载入数据时，是否显示‘进度’提示
        "bServerSide" : true, //是否启动服务器端数据导入
        "bStateSave" : false, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
        "bJQueryUI" : true, //是否使用 jQury的UI theme
        "aLengthMenu" : [5, 10, 15], //更改显示记录数选项
        "iDisplayLength" : 10, //默认显示的记录数
        "bAutoWidth" : true, //是否自适应宽度 update\
        "bScrollCollapse" : false, //是否开启DataTables的高度自适应，当数据条数不够分页数据条数的时候，插件高度是否随数据条数而改变
        "bPaginate" : true, //是否显示（应用）分页器
        "bInfo" : true, //是否显示页脚信息，DataTables插件左下角显示记录数
        "sPaginationType" : "full_numbers", //详细分页组，可以支持直接跳转到某页
        "bSort" : true, //是否启动各个字段的排序功能
        "aaSorting" : [[5, "ASC"]], //默认的排序方式，第3列，升序排列
        "bFilter" : false, //是否启动过滤、搜索功能
        "sScrollX": "100%",
		"sScrollXInner": 1695,
	    "sAjaxSource":"sys/report/yw/loanDetail",
        "fnServerData":retrieveData,  //自定义数据获取函数       
		"aoColumns" : [ {
			"mDataProp" : "contractCode",
			"sTitle" : "合同编号",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center"
		}, {
			"mDataProp" : "loanBorrower",
			"sTitle" : "贷款人",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center"
		}, {
			"mDataProp" : "loanProduct",
			"sTitle" : "贷款产品",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center",
			"mRender": function (data, display, row) {	
				var returnStr = top.SYS_BASE_DATA['Loan_Product_Code'][data];
				return returnStr;
			}
		}, {
			"mDataProp" : "deadlineTotal",
			"sTitle" : "贷款期数",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center"
		}, {
			"mDataProp" : "deadlineReal",
			"sTitle" : "已还款期数",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center"
		}, {
			"mDataProp" : "contractDate",
			"sTitle" : "贷款日期",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center",
			"mRender": function (data, display, row) {
				var value = '';
				if(_is_empty(data)){
					value = '';
				}else{
					value = new Date(data).format('yyyy-MM-dd');
				}
				
	            return value;
		     }
		}, {
			"mDataProp" : "payDate",
			"sTitle" : "放款日期",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center",
			"mRender": function (data, display, row) {
				var value = '';
				if(_is_empty(data)){
					value = '';
				}else{
					value = new Date(data).format('yyyy-MM-dd');
				}
				
	            return value;
		     }
		}, {
			"mDataProp" : "capitalTotal",
			"sTitle" : "贷款金额（元）",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center"
		}, {
			"mDataProp" : "capitalReal",
			"sTitle" : "已还本金（元）",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center"
		}, {
			"mDataProp" : "incometotal",
			"sTitle" : "已有收益（元）",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center"
		}, {
			"mDataProp" : "plantotal",
			"sTitle" : "预期收益（元）",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center"
		}, {
			"mDataProp" : "loanSourceName",
			"sTitle" : "业务员",
			"bSortable": true,
			"sDefaultContent" : "",
			"sClass" : "center"
		}],
		"oLanguage": {
            "sUrl":parent.basePath+"static_resources/language/lang-cn.txt" //这个是国际化，也就是汉化的各种文字数据源，写对url就行了
        },
        "footerCallback": function ( row, data, start, end, display ) {
            var api = this.api(), data;
            var intVal = function (i) {
                return typeof i === 'string' ?
                    i.replace(/[\$,]/g, '')*1 :
                    typeof i === 'number' ?
                        i : 0;
            };
            //贷款金额合计
            pageTotal7 = api.column(7, { page: 'current'}).data().reduce( function (a, b) {
            	return intVal(a) + intVal(b);
          	}, 0);
            $('#capitalTotalPage').html(pageTotal7);

            //已还本金合计
            pageTotal8 = api.column(8, { page: 'current'}).data().reduce( function (a, b) {
            	return intVal(a) + intVal(b);
          	}, 0);
            $('#capitalRealPage').html(pageTotal8);
            
          //已有收益合计
            pageTotal9 = api.column(9, { page: 'current'}).data().reduce( function (a, b) {
            	return intVal(a) + intVal(b);
          	}, 0);
            $('#incomeTotalPage').html(pageTotal9);
            
          //预期收益合计
            pageTotal10 = api.column(10, { page: 'current'}).data().reduce( function (a, b) {
            	return intVal(a) + intVal(b);
          	}, 0);
            $('#planTotalPage').html(pageTotal10);
        }
	});
	
	//查询事件
	$('input[name="query_btn"]').click(function(){
		fnDraw();
	});
};

//重新刷新列表数据
var fnDraw = function(){
	$('#enterprise').dataTable().fnDraw();
};

//自定义数据获取函数
var retrieveData = function ( sSource, aoData, fnCallback ) {
		var array = $("#_form_search_default").serializeArray();
		//array.push({'name':'beanProxy[loanStatus_GreaterThanOrEqualTo]','value':5});		
		aoData.push({'name':'v2hldghlcib0agugzgf0ysbhy2nlc3m','value':1});
		aoData = parent._set_query_conditions(aoData,array);
	        $.ajax( {
	                type: "POST", 
	                url: sSource, 
	                cache : false,
	                dataType : "json",
	                data : aoData, 
	                success: function(resp) {
	                	if(resp && resp.state == 200){
	                		footer = resp.footer;
	                		fnCallback(resp.datagrid);
	                		 
//	                		if(footer){
//	                			$('#queryTotal').html('$'+footer.capitalRealSum +' ( $'+ footer.capitalTotalSum +' total)');
//	                		}
	                		$('#capitalTotalSum').html('总计：0');
                			$('#capitalRealSum').html('总计：0');
                			$('#incomeTotalSum').html('总计：0');
                			$('#planTotalSum').html('总计：0');
	                		if(footer.capitalTotalSum){
	                			$('#capitalTotalSum').html('总计：'+footer.capitalTotalSum);
	                		}
	                		if(footer.capitalRealSum){
	                			$('#capitalRealSum').html('总计：'+footer.capitalRealSum);
	                		}
	                		if(footer.incomeTotalSum){
	                			$('#incomeTotalSum').html('总计：'+footer.incomeTotalSum);
	                		}
	                		if(footer.planTotalSum){
	                			$('#planTotalSum').html('总计：'+footer.planTotalSum);
	                		}
	                		return false;
	                	}
	                	fnCallback(null);
	            }
	        });
};

//初始化
$(function(){
	initGrid();
	$('#loanProduct').mSelect({
		width:100,
		baseCode:'Loan_Product_Code'
	});
	
	//导出
	$('input[name="excel_btn"]').click(function(){
		var array = $("#_form_search_default").serializeArray();
		var queryParams = top.array_to_obj(array, 'name', 'value');
		var condition = '';
		for(var key in queryParams ){
			condition=condition+key+'='+queryParams[key]+'&';
		}
		condition =condition+'isNonPage=1';
       var url = 'sys/report/yw/loanDetailExcelOut';
       if(''!=condition){
    	   url = url + '?'+ condition;
       }
       
		window.location.href = url;
	});
});